<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%" class="tag-dialog">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
        class="tag-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <Icon icon="ep:info-filled" class="section-icon" />
            <span>基本信息</span>
          </div>

          <el-form-item label="标签内容" prop="content" class="form-item">
            <el-input
              v-model.trim="formData.content"
              placeholder="请输入标签内容"
              class="form-input"
              clearable
              maxlength="20"
              show-word-limit
            >
              <template #prefix>
                <Icon icon="ep:price-tag" class="input-icon" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="排序" prop="sort" class="form-item">
            <el-input-number
              class="form-number"
              :min="1"
              :max="100"
              :step="1"
              v-model="formData.sort"
              placeholder="请输入排序"
            />
            <div class="input-tip">
              <Icon icon="ep:info-filled" class="tip-icon" />
              <span>数值越小排序越靠前</span>
            </div>
          </el-form-item>
        </div>

        <!-- 颜色配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <Icon icon="ep:brush" class="section-icon" />
            <span>颜色配置</span>
          </div>

          <el-form-item label="标签颜色" prop="bgColor" class="form-item">
            <div class="color-picker-container">
              <div class="preset-colors">
                <div
                  v-for="(item, index) in defaultColors.slice(2)"
                  :key="index + 'color'"
                  :class="['color-item', { 'color-active': item === formData.bgColor }]"
                  @click="chooseBgColor(item)"
                >
                  <span class="color-span" :style="{ background: item }"></span>
                </div>
              </div>
              <el-color-picker
                v-model="formData.bgColor"
                show-alpha
                @change="bgPickerChange"
                class="custom-color-picker"
              />
            </div>
          </el-form-item>

          <el-form-item label="文字颜色" prop="textColor" class="form-item">
            <div class="color-picker-container">
              <div class="preset-colors">
                <div
                  v-for="(item, index) in [
                    defaultColors[1],
                    defaultColors[0],
                    ...[...defaultColors].slice(2, 6),
                    ...[...defaultColors].slice(8).reverse()
                  ]"
                  :key="index + 'textColor'"
                  :class="['color-item', { 'color-active': item === formData.textColor }]"
                  @click="chooseTextColor(item)"
                >
                  <span class="color-span" :style="{ background: item }"></span>
                </div>
              </div>
              <el-color-picker
                v-model="formData.textColor"
                show-alpha
                @change="textPickerChange"
                class="custom-color-picker"
              />
            </div>
          </el-form-item>
        </div>

        <!-- 预览区域 -->
        <div class="form-section">
          <div class="section-title">
            <Icon icon="ep:view" class="section-icon" />
            <span>预览效果</span>
          </div>

          <el-form-item label="预览" class="form-item">
            <div class="preview-container">
              <EntTag
                :content="formData.content || '标签预览'"
                :bgColor="formData.bgColor"
                :textColor="formData.textColor"
                class="preview-tag"
              />
              <div class="preview-info">
                <p class="preview-text">这是标签的预览效果</p>
                <p class="preview-desc">实际显示效果可能因环境而异</p>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          class="delete-btn"
          type="danger"
          v-hasPermi="['crm:label:delete']"
          v-if="formType === 'update'"
          @click="delForm"
        >
          <Icon icon="ep:delete" class="btn-icon" />
          删除
        </el-button>
        <div class="footer-actions">
          <el-button class="cancel-btn" @click="dialogVisible = false">
            <Icon icon="ep:close" class="btn-icon" />
            取消
          </el-button>
          <el-button
            type="primary"
            class="submit-btn"
            :disabled="formLoading"
            :loading="formLoading"
            @click="submitForm"
          >
            <Icon icon="ep:check" class="btn-icon" v-if="!formLoading" />
            {{ formLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as TagGroupApi from '@/api/ent/tag/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  setId: undefined,
  content: undefined,
  bgColor: 'rgba(2, 129, 252, 1)',
  textColor: '#ffffff',
  sort: undefined,
  id: undefined
})
const formRules = reactive({
  content: [{ required: true, message: '标签内容不能为空', trigger: 'blur' }],
  bgColor: [{ required: true, message: '标签颜色不能为空', trigger: 'blur' }],
  textColor: [{ required: true, message: '文字颜色不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const defaultColors = ref([
  '#000000',
  '#ffffff',
  'rgba(2, 129, 252, 1)',
  'rgba(43, 151, 255, 1)',
  'rgba(80, 168, 252, 1)',
  'rgba(124, 190, 252, 1)',
  'rgba(255, 0, 0, 1)',
  'rgba(252, 50, 50, 1)',
  'rgba(255, 98, 98, 1)',
  'rgba(252, 143, 143, 1)',
  'rgba(255, 208, 0, 1)',
  'rgba(252, 214, 45, 1)',
  'rgba(254, 225, 97, 1)',
  'rgba(251, 232, 147, 1)'
])

const chooseBgColor = (color) => {
  formData.value.bgColor = color
}
const chooseTextColor = (color) => {
  formData.value.textColor = color
}
const bgPickerChange = (color) => {
  formData.value.bgColor = color
}
const textPickerChange = (color) => {
  formData.value.textColor = color
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type == 'create') formData.value.setId = id
  if (type == 'update') {
    formData.value = await TagGroupApi.getTag(id)
  }
  formLoading.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await TagGroupApi.createTag(data)
      message.success(t('common.createSuccess'))
    }
    if (formType.value === 'update') {
      await TagGroupApi.updateTag(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    setId: undefined,
    content: undefined,
    bgColor: 'rgba(2, 129, 252, 1)',
    textColor: '#ffffff',
    sort: undefined,
    id: undefined
  }
  formRef.value?.resetFields()
}
/*删除*/
const delForm = () => {
  ElMessageBox.confirm('确定要删除当前标签吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await TagGroupApi.deleteTag(formData.value.id)
      dialogVisible.value = false
      if (res) ElMessage.success('删除成功!')
      emit('success')
    })
    .catch(() => {})
}
</script>

<style scoped lang="scss">
// 对话框样式
.tag-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;

    .el-dialog__header {
      background: linear-gradient(135deg, #667eea 0%, #0052cc 100%);
      color: white;
      padding: 20px 24px;

      .el-dialog__title {
        color: white;
        font-size: 18px;
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        .el-dialog__close {
          color: rgba(255, 255, 255, 0.8);
          font-size: 18px;

          &:hover {
            color: white;
          }
        }
      }
    }

    .el-dialog__body {
      padding: 0;
    }

    .el-dialog__footer {
      padding: 0;
      border-top: 1px solid #f1f5f9;
    }
  }
}

// 表单容器
.form-container {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.tag-form {
  .form-section {
    margin-bottom: 32px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 区域标题
.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f1f5f9;

  .section-icon {
    color: #667eea;
    font-size: 18px;
  }

  span {
    font-size: 16px;
    font-weight: 600;
    color: #374151;
  }
}

// 表单项
.form-item {
  margin-bottom: 24px;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
    line-height: 1.6;
  }

  :deep(.el-form-item__content) {
    line-height: normal;
  }
}

// 输入框样式
.form-input {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focus {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }

  .input-icon {
    color: #9ca3af;
    font-size: 16px;
  }
}

// 数字输入框
.form-number {
  width: 200px;

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focus {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }
}

// 颜色选择器容器
.color-picker-container {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.preset-colors {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.color-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    border-color: #d1d5db;
    transform: scale(1.1);
  }

  &.color-active {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  }
}

.color-span {
  display: block;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.custom-color-picker {
  :deep(.el-color-picker__trigger) {
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    width: 40px;
    height: 40px;
    transition: all 0.2s ease;

    &:hover {
      border-color: #667eea;
    }
  }
}

// 预览容器
.preview-container {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

.preview-tag {
  flex-shrink: 0;
}

.preview-info {
  .preview-text {
    margin: 0 0 4px 0;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
  }

  .preview-desc {
    margin: 0;
    font-size: 12px;
    color: #9ca3af;
  }
}

// 输入提示
.input-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  border-radius: 6px;
  margin-left: 10px;

  .tip-icon {
    color: #0ea5e9;
    font-size: 14px;
  }

  span {
    font-size: 13px;
    color: #0369a1;
  }
}

// 对话框底部
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.delete-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 6px;
    font-size: 14px;
  }

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
  }
}

.cancel-btn {
  padding: 10px 20px;
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  background: white;
  color: #6b7280;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 6px;
    font-size: 14px;
  }

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }
}

.submit-btn {
  padding: 10px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #0052cc 100%);
  border: none;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 6px;
    font-size: 14px;
  }

  &:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

// H5 响应式设计
@media (max-width: 768px) {
  .tag-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 20px auto;

      .el-dialog__header {
        padding: 16px 20px;

        .el-dialog__title {
          font-size: 16px;
        }
      }
    }
  }

  .form-container {
    padding: 20px;
    max-height: 60vh;
  }

  .tag-form {
    :deep(.el-form-item__label) {
      font-size: 14px;
    }
  }

  .section-title {
    span {
      font-size: 15px;
    }
  }

  .color-picker-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .preview-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 12px;

    .footer-actions {
      width: 100%;

      .cancel-btn,
      .submit-btn {
        flex: 1;
        justify-content: center;
      }
    }

    .delete-btn {
      width: 100%;
      justify-content: center;
    }
  }
}

@media (max-width: 480px) {
  .tag-dialog {
    :deep(.el-dialog) {
      width: 100% !important;
      margin: 0;
      height: 100vh;
      border-radius: 0;
    }
  }

  .form-container {
    padding: 16px;
    max-height: calc(100vh - 140px);
  }

  .form-section {
    margin-bottom: 24px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .form-number {
    width: 100%;
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .tag-dialog {
    :deep(.el-dialog) {
      background: #1e293b;

      .el-dialog__body {
        background: #1e293b;
      }
    }
  }

  .form-container {
    background: #1e293b;
  }

  .section-title {
    border-color: #334155;

    span {
      color: #f1f5f9;
    }
  }

  .form-item {
    :deep(.el-form-item__label) {
      color: #e2e8f0;
    }
  }

  .preview-container {
    background: #334155;
    border-color: #475569;

    .preview-info {
      .preview-text {
        color: #f1f5f9;
      }

      .preview-desc {
        color: #94a3b8;
      }
    }
  }

  .input-tip {
    background: #1e3a8a;
    border-color: #1e40af;

    span {
      color: #93c5fd;
    }
  }

  .dialog-footer {
    background: #0f172a;
    border-color: #334155;
  }
}
</style>
